/*
 * CROSInterceptor.java
 * Copyright 2021 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package cn.org.itool.web.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 描述:
 * 解决跨域问题
 */
@Log4j2
public class CROSInterceptor implements HandlerInterceptor {

    @Value("${i-tool.auth.head-token-name}")
    private String headTokenName;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
//            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("P3P", "CP=CAO PSA OUR");
            if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
                response.addHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,TRACE,OPTIONS");
                response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept,"+headTokenName);
                response.addHeader("Access-Control-Max-Age", "120");
            }
        } catch (Exception e) {
            log.error("设置CROS信息异常", e);
        }
        return true;
    }
}
